# -*- coding: utf-8 -*-
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from sclass.models import Class
from sclass.SclassSerializer import SclassSerializer
from django.utils.six import BytesIO
import json

# Create your views here.

@csrf_exempt
def ShowClass(request):
    '''

    实现 list all object and add object
    :param request:
    :return:
    '''

    if request.method == 'GET':
        querset = Class.objects.all()
        seri = SclassSerializer(querset,many=True)
        return  JsonResponse(seri.data,safe=False)

    elif request.method == 'POST':
        '''
        request  json data
        
        '''

        data = JSONParser().parse(request)
        seri = SclassSerializer(data=data)

        if seri.is_valid():
            seri.save()
            return JsonResponse(seri.data, status=201)

        return  JsonResponse(seri.errors,safe=False)

    else:
        return JsonResponse('{"error":"unsuport request method"}', safe=False)

@csrf_exempt
def Control(request):
    '''
    default get object by code
    put to update old object
    delete to del old
    :param request:
    :return:
    '''

    if request.method == 'GET':
        seri = SclassSerializer(Class.objects.get(code=request.GET['code']))
        return  JsonResponse(seri.data,safe=False)

    elif request.method == 'PUT':

        getdata = json.dumps(JSONParser().parse(request))

        stream = BytesIO(getdata)
        data = JSONParser().parse(stream)

        #第一种方式
        #seri = SclassSerializer(data=data)

        #第二种方式
        seri = SclassSerializer(Class.objects.get(code=request.GET['code']),data=data)

        if seri.is_valid():
            # 第一种方式
            #seri.update(Class.objects.get(code=request.GET['code']),seri.validated_data)

            #第二种方式
            seri.save()

            print("to valid ")
            return JsonResponse(seri.data,status=201)

        return JsonResponse(seri.errors, status=400)

    elif request.method == 'DELETE':
        delclass = Class.objects.get(code=request.GET['code'])
        delclass.delete()

        return HttpResponse(status=204)

from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view(['GET','POST'])
def ListClass(request):
    """
    实现 list all object and add object
    :param request:
    :return:

    """
    if request.method == 'GET':
        querset = Class.objects.all()
        seri = SclassSerializer(querset,many=True)
        return  JsonResponse(seri.data,safe=False)

    elif request.method == 'POST':

        seri = SclassSerializer(data=request.data)
        if seri.is_valid():
            seri.save()

            return  Response(seri.data,status=status.HTTP_200_OK)

        return  Response(seri.errors,status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET', 'PUT', 'DELETE'])
def CrudControl(request):
    """
    查询单个项目
    更新项目内容
    删除具体项目

    :param request:
    :return:
    """

    try:
        getclass = Class.objects.get(code=request.GET['code'])

    except Class.DoseNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)


    if request.method == 'GET':
        getclass = SclassSerializer(getclass)
        return  Response(getclass.data)

    elif request.method == 'PUT':
        seri = SclassSerializer(getclass,data=request.data)

        if seri.is_valid():
            seri.save()
            return Response(seri.data,status.HTTP_200_OK)

        return Response(seri.errors,status=status.HTTP_400_BAD_REQUEST)


    elif request.method == 'DELETE':
        getclass.delete()

        return HttpResponse("delete is ok",status=status.HTTP_200_OK)



from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status


class SclassList(APIView):
    """
    by  CLASS to show all and add object

    """

    def get(self,request,format=None):
        querset = Class.objects.all().order_by('code')
        seris = SclassSerializer(querset,many=True)
        return Response(seris.data,status=status.HTTP_200_OK)


    def post(self,request,format=None):
        seri = SclassSerializer(data=request.data)

        if seri.is_valid():
            seri.save()
            return Response(seri.data,status=status.HTTP_200_OK)

        return Response(seri.errors,status=status.HTTP_400_BAD_REQUEST)



class SclassModify(APIView):
    """
     get one
     modify one
     del one
    """
    def getone(self,getcode):

        try:
            return  Class.objects.get(code=getcode)

        except Class.DoseNotExist:
            return Http404

    def get(self,request,format=None):
        clas = self.getone(request.GET['code'])
        seri = SclassSerializer(clas)

        return Response(seri.data)


    def put(self,request,format=None):
        clas = self.getone(request.GET['code'])
        seri = SclassSerializer(clas,data=request.data)

        if seri.is_valid():
            seri.save()
            return  Response(seri.data)

        return Response(seri.errors,status=status.HTTP_400_BAD_REQUEST)


    def delete(self,request,format=None):
        clas = self.getone(request.GET['code'])
        clas.delete()

        return Response("DELETE IS RUUNING ",status=status.HTTP_200_OK)


